package com.hmall.search.listener;

import cn.hutool.json.JSONUtil;
import com.hmall.common.client.ItemClient;
import com.hmall.common.pojo.Item;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class SpringRabbitListener {
@Autowired
private ItemClient itemClient;
@Autowired
private StringRedisTemplate redisTemplate;

    @Bean
    Queue statusUpdateQueue() {
        return new Queue("statusUpdate.queue", true); // durable=true 表示持久化的队列
    }

    @RabbitListener(queues = "statusUpdate.queue")
    public void updateListener(String msg){
        // TODO 重新查询热门商品
        if ("update".equals(msg)){
            //查询热门商品
         List<Item> items = itemClient.hotItems();
            //封装到redis中
            if (items != null && items.size() > 0){
                redisTemplate.opsForValue().set("hotItems", JSONUtil.toJsonStr(items));
            }
        }
    }
}